package com.aloda.ojcommon.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aloda.ojcommon.constant.RedisConstant;
import com.aloda.ojcommon.context.UserBaseContext;
import com.aloda.ojcommon.domain.dto.UserCacheDTO;
import com.aloda.ojcommon.properties.TokenProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    @Resource
    private TokenProperties tokenProperties;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取token
        String token = request.getHeader(tokenProperties.getUserTokenName());
        // 2.从redis中获取token对应的用户
        String key = RedisConstant.USER_TOKEN + token;
        String userInfo = stringRedisTemplate.opsForValue().get(key);
        UserCacheDTO userCacheDTO = JSONUtil.toBean(userInfo, UserCacheDTO.class);
        // 保存用户
        if (BeanUtil.isNotEmpty(userCacheDTO)) {
            UserBaseContext.saveUser(userCacheDTO);
        }
        // 3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserBaseContext.removeUser();
    }
}
